package cn.com.connected.common.config.jackson;

import cn.com.connected.common.config.jackson.serialize.MyBeanSerializerModifier;
import cn.com.connected.common.utils.DataFormatUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.util.Date;

@Configuration
public class ContentMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    public ContentMappingJackson2HttpMessageConverter() {
        super();
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));

        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                return DataFormatUtils.convert(jsonParser.getText());
            }
        });
        objectMapper.registerModule(module);
    }

    //决定是否使用该类作为消息转换器进行序列化。
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return super.canWrite(clazz, mediaType);
    }
}